package com.wyzy.spring.demo;

import com.wyzy.spring.object.Person;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/demo01")
public class demo01 {
    @RequestMapping("/d1")
    public String d1(@RequestBody Person person){
        return "接收参数：" + person;
    }
    @RequestMapping("/d2/{id}")
    public String d2(@PathVariable Integer id){
        return "接收参数：" + id;
    }
    @RequestMapping("/d3")
    public String d3(@RequestPart MultipartFile file){
        String fileName = file.getName();
        String fileOriginalName = file.getOriginalFilename();
        String fileType = file.getContentType();
        return "接收到参数fileName:" +fileName + ",\nfileOriginalName:" + fileOriginalName
                + ",\nfileType:" + fileType;
    }
    /*
    * 获取Cookie
    */
    @RequestMapping("/d4")
    public String d4(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        StringBuilder builder = new StringBuilder();
        if(cookies != null){
            for(Cookie cookie:cookies){
                builder.append(cookie.getName() + ":" + cookie.getValue());
            }
        }
        return "接收到cookie：" + builder;
    }
    @RequestMapping("/d5")
    public String d5(@CookieValue("id") Integer id){
        return "接收到class：" + id;
    }
    /*
    * 设置session
    */
    @RequestMapping("/d6")
    public String d6(HttpServletRequest request){
        HttpSession session = request.getSession();
        if(session != null){
            session.setAttribute("name","zhangsan");
        }
        return "session设置成功";
    }
    //获取session
    @RequestMapping("/d7")
    public String d7(HttpSession session){
        String name = (String)session.getAttribute("name");
        return "获取name：" + name;
    }
    //获取session（注解）
    @RequestMapping("/d8")
    public String d8(@SessionAttribute("name") String name){
        return "获取name：" + name;
    }
    //获取Header
    @RequestMapping("/d9")
    public String d9(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        return "获取userAgent：" + userAgent;
    }
    //通过注解获取Header
    @RequestMapping("/d10")
    public String d10(@RequestHeader("User-Agent") String userAgent){
        return "获取userAgent：" + userAgent;
    }
}
